import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { util_Db_Add, util_Db_PageList, util_Db_Delete, util_Db_Update } from '@/common/util/db';
import { Good } from './assets/good.entity';
import { Good_Update_Dto, Good_Create_Dto, Good_Find_Dto } from './assets/good.dto';
import { Product } from '../product/assets/product.entity';

@Injectable()
export class Good_Service {
  constructor(
    @InjectRepository(Good)
    private good_Repository: Repository<Good>,
    @InjectRepository(Product)
    private product_Repository: Repository<Product>,
  ) {}

  async good_Create(body: Good_Create_Dto) {
    const product = this.product_Repository.create({
      id: body.productId,
    });
    return await util_Db_Add({
      createDto: { ...body, product },
      repository: this.good_Repository,
    });
  }

  async good_FindByPage(query: Good_Find_Dto) {
    return await util_Db_PageList({
      queryBuilder: this.good_Repository
        .createQueryBuilder('good')
        .leftJoin('good.product', 'product')
        .leftJoin('product.platform', 'platform')
        .select([
          'good.id AS id',
          'good.account AS account',
          'good.password AS password',
          'good.seatsNum AS seatsNum',
          'good.goodStartTime AS goodStartTime',
          'good.goodEndTime AS goodEndTime',
          'platform.id AS platformId',
          'platform.platFormName AS platFormName',
          'product.id AS productId',
          'product.productName AS productName',
          'product.productPrice AS productPrice',
          'product.productImg AS productImg',
          'product.productNum AS productNum',
          'product.productName AS productName',
        ]),
      query: {
        'product.id': query.productId,
        'product.platform': query.platformId,
        'good.account': query.account,
        size: query.size,
        page: query.page,
      },
      isRaw: true,
    });
  }

  async good_FindOneById(id: number) {
    return await this.good_Repository
      .createQueryBuilder('good')
      .leftJoin('good.product', 'product')
      .andWhere(`good.id = :id`, { id: id })
      .getOne();
  }

  async good_Update(body: Good_Update_Dto) {
    const product = this.product_Repository.create({
      id: body.productId,
    });
    return await util_Db_Update({
      findOne: async () => await this.good_FindOneById(body.id),
      updateDto: { ...body, product },
      repository: this.good_Repository,
    });
  }

  async good_Remove(id: number) {
    return await util_Db_Delete({
      findOne: () => this.good_FindOneById(id),
      id,
      repository: this.good_Repository,
    });
  }
}
